<template>
  <div>
    <a-card :bordered="false">
      <a-form ref="modifyPriceForm" :model="form" :style="{ width: '100%' }" layout="horizontal" auto-label-width>
        <div class="base-info-item">
          <h4>活动信息</h4>
          <div class="form-item-view">
            <a-form-item field="promotionName" label="活动名称" :rules="[REQUIRED]">
              <a-input v-model="form.promotionName" allow-clear :style="{ width: '260px' }" placeholder="请填写活动名称" />
            </a-form-item>
            <a-form-item field="promotionName" label="活动时间">
              <a-range-picker style="width: 260px; margin-bottom: 20px;" v-model="rangeTime" />
            </a-form-item>
            <a-form-item field="couponActivityType" label="优惠券活动类型">
              <a-radio-group type="button" v-model="form.couponActivityType">
                <a-radio value="REGISTERED">新人发券</a-radio>
                <a-radio value="SPECIFY">精确发券</a-radio>
                <a-radio value="AUTO_COUPON">自动赠券</a-radio>
                <a-radio value="INVITE_NEW">邀新赠券</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="couponFrequencyEnum" label="领取频率"  v-if="form.couponActivityType === 'AUTO_COUPON'">
              <a-radio-group type="button" v-model="form.couponFrequencyEnum">
                <a-radio value="DAY">每日</a-radio>
                <a-radio value="WEEK">每周一次</a-radio>
                <a-radio value="MONTH">每月一次</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="activityScope" label="活动范围" v-if="form.couponActivityType === 'SPECIFY'">
              <a-radio-group type="button" v-model="form.activityScope">
                <a-radio value="ALL">全部会员</a-radio>
                <a-radio value="DESIGNATED">指定会员 </a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item field="scopeType" label="活动范围" v-if="
              form.couponActivityType === 'SPECIFY' &&
              form.activityScope === 'DESIGNATED'
            ">
              <a-button type="primary" @click="addVip">
                选择会员
              </a-button>
            </a-form-item>
            <a-form-item v-if="
              form.couponActivityType === 'SPECIFY' &&
              form.activityScope === 'DESIGNATED'
            ">
              <a-table :columns="userColumns" :data="selectedMember">
                <template #del="{ rowIndex }">
                  <a-button type="text" status="danger" @click='delUser(rowIndex)'>删除</a-button>
                </template>
              </a-table>
            </a-form-item>
          </div>
        </div>
        <h4>配置优惠券</h4>
        <div class="form-item-view">
          <a-form-item field="scopeType" label="选择优惠券">
            <a-button type="primary"  @click="showSelector">选择优惠券</a-button>
          </a-form-item>
          <a-form-item field="scopeType" label="赠送配置">
            <a-table :columns="columns" w-full :data="selectCouponList">
              <template #scopeType="{ record }">
                {{ clientTypeWay(record.scopeType) }}
              </template>
              <template #price="{ record }">
                <span v-if="record.price">{{ unitPrice(record.price, '¥') }}</span>
                <span v-else>{{ `${record.couponDiscount}折` }}</span>
              </template>
              <template #sendNum="{ rowIndex }">
                <a-input v-model="form.couponActivityItems[rowIndex].num" placeholder="赠送数量"></a-input>
              </template>
              <template #couponName="{ rowIndex }">
                <a-button type="text" status="danger" @click="delCoupon(rowIndex)">删除</a-button>
              </template>
            </a-table>
          </a-form-item>
        </div>
      </a-form>
      <a-button style="margin-right: 5px" @click="closeCurrentPage">返回</a-button>
      <a-button type="primary"  @click="handleSubmit">提交</a-button>
    </a-card>
  </div>
  <couponselector ref="couponLayout" @couponlist="couponlist"></couponselector>
  <a-modal v-model:visible="checkUserList" width="1200px">
    <userList ref="memberLayout" @callback="callbackSelectUser"  :selectedList="selectedMember"></userList>
  </a-modal>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from "vue"
import couponselector from '@/components/couponselector/index.vue';
import userList from '@/views/member/member-list/list.vue';
import { unitPrice } from '@/utils/filters';
import { useRouter } from 'vue-router';
import { REQUIRED } from '@/utils/validator';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { saveActivityCoupon } from '@/api/promotion';
import { Message } from '@arco-design/web-vue';
import { clientTypeWay, dayFormatHHssMM } from '@/utils/filters';

const router = useRouter()
const selectCouponList = ref([]) as any // 选择的优惠券列表
// 优惠卷列表
const columns: any = [
  {
    title: '优惠券名称',
    dataIndex: 'couponName',
    width: 300
  },
  {
    title: '品类描述',
    dataIndex: 'scopeType',
    width: 300,
    slotName: 'scopeType'
  },
  {
    title: '面额/折扣',
    dataIndex: 'price',
    width: 300,
    slotName: 'price'
  },
  {
    title: '赠送数量',
    dataIndex: 'couponName',
    width: 300,
    slotName: 'sendNum'
  },
  {
    title: '操作',
    dataIndex: 'couponName',
    width: 300,
    slotName: 'couponName'
  },
]
// 会员列表
const userColumns: any = [
  {
    title: '用户名称',
    dataIndex: 'nickName',
    width: 375
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    width: 375
  },
  {
    title: '最后登录时间',
    dataIndex: 'lastLoginDate',
    width: 375
  },
  {
    title: '操作',
    dataIndex: 'del',
    width: 375,
    slotName: 'del'
  },
]
const form = ref<any>({
  promotionName: "", // 活动名称
  activityScope: "ALL", // 活动范围 ，默认全体发券
  couponActivityType: "REGISTERED", // 触发活动方式 默认新人赠券
  couponFrequencyEnum:"MONTH", //选择周期
  startTime: "", // 开始时间
  endTime: "", // 结束时间
  memberDTOS: [], // 指定会员范围
  couponActivityItems: [

  ], // 优惠券列表
});
const rangeTime = ref([]) // 时间区间
const couponLayout = ref(null) as any // 优惠券选择器
const memberLayout = ref(null) as any // 选择会员
const checkUserList = ref<boolean>(false) // 选择会员弹框是否显示
const selectedMember = ref<Array<any>>([]); // 已选会员列表数据
const modifyPriceForm = ref<FormInstance>()
const reSelectCoupon = () => {
  form.value.couponActivityItems = selectCouponList.value.map((item: any) => {
    return {
      num: 0,
      couponId: item.id,
    }
  })
}
const showSelector = () => {
  couponLayout.value.visible = true
}
const couponlist = (val: any) => {
  selectCouponList.value.push(...val)
  const map = new Map();
  selectCouponList.value = selectCouponList.value.map((item: any) => {
    return map.set(item.id, item);
  })
  selectCouponList.value = [...map.values()];
  reSelectCoupon()
}
// 删除
const delCoupon = (idx: any) => {
  selectCouponList.value.splice(idx, 1)
  reSelectCoupon()
}
// 更新选择的会员
const reSelectMember = () => {
  form.value.memberDTOS = selectedMember.value.map((item: any) => {
    return {
      nickName: item.nickName,
      id: item.id,
    };
  })
}
// 选择会员
const addVip = () => {
  memberLayout.value.selectedMember = false
  checkUserList.value = true
}
// 子组件传过来的值
const callbackSelectUser = (val: any): void => {
  // 每次将返回的数据回调判断
  const findUser = selectedMember.value.find((item: any) => {
    return item.id === val.id;
  }) as any;
  // 如果没有则添加
  if (!findUser) {
    selectedMember.value.push({ ...val })
  } else {
    // 有重复数据就删除
    selectedMember.value.forEach((item: any, index: any) => {
      if (item.id === findUser.id) {
        selectedMember.value.splice(index, 1)
      }
    })
  }
  reSelectMember()
}

// 删除会员
const delUser = (idx: any) => {
  selectedMember.value.splice(idx, 1)
  reSelectMember()
}
// 返回
const closeCurrentPage = () => {
  router.push({ name: 'coupon-activity' })
}
// 提交
const handleSubmit = async () => {
  form.value.startTime = dayFormatHHssMM(rangeTime.value[0])
  form.value.endTime = dayFormatHHssMM(rangeTime.value[1])
  const params = JSON.parse(JSON.stringify(form.value))
  // 判断当前是否是精准发券功能
  if(params.couponActivityType !== 'SPECIFY'){
    // 如果不是默认
    params.activityScope = 'ALL'
  }
  delete params.id;
  const auth = await modifyPriceForm.value?.validate();
  if (!auth) {
    saveActivityCoupon(params).then((res: any) => {
      if (res.data.success) {
        Message.success('优惠券活动创建成功');
        router.push({ name: 'coupon-activity' })
      }
    })
  }
}
</script>

<style lang="less" scoped>
h4 {
  margin-bottom: 10px;
  padding: 0 10px;
  border: 1px solid #ddd;
  background-color: #f8f8f8;
  font-weight: bold;
  color: #333;
  font-size: 14px;
  line-height: 40px;
  text-align: left;
}

.describe {
  font-size: 12px;
  margin-left: 10px;
  color: #999;
}

.effectiveDays {
  font-size: 12px;
  color: #999;

  >* {
    margin: 0 4px;
  }
}
</style>
